#!/usr/bin/python

from math import sqrt, floor, hypot
import Image

def dist(x1, x2):
    return hypot(x1[0] - x2[0], x1[1] - x2[1])

def perspective_correction(im, ul, ll, lr, ur):
    w = int(0.5 * (dist(ul, ur) + dist(ll, lr)))
    h = int(0.5 * (dist(ul, ll) + dist(ur, lr)))
    return im.transform(
        (w, h), Image.QUAD,
        (ul[0], ul[1], ll[0], ll[1], lr[0], lr[1], ur[0], ur[1]),
        Image.BICUBIC)
